package com.fht.spring_boot_study.model.common.service.impl;

import com.fht.spring_boot_study.model.common.entity.ImageType;
import com.fht.spring_boot_study.model.common.entity.ResourceConfigBean;
import com.fht.spring_boot_study.model.common.entity.ResultEntity;
import com.fht.spring_boot_study.model.common.service.ImageService;
import com.fht.spring_boot_study.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class ImageServiceImpl implements ImageService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);
    @Autowired
    private ResourceConfigBean resourceConfigBean;

    @Override
    public ResultEntity<String> uploadImage(MultipartFile file, String imageType) {
        if (file.isEmpty()) {
            return new ResultEntity<>(
                    ResultEntity.ResultStatus.FAILED.code, "File is empty");
        }

        String destFolderString = String.format("%s%s",
                resourceConfigBean.getLocalPathForWindow(), imageType);
        File destFolder = new File(destFolderString);
        if (!destFolder.exists()) {
            destFolder.mkdir();
        }

        String imageName = String.format("%s.%s",
                System.currentTimeMillis(),
                FileUtil.getFileType(file.getOriginalFilename()));
        String abstactPath = String.format("%s/%s",
                destFolderString, imageName);
        String relativePath = String.format("%s%s/%s",
                resourceConfigBean.getResourcePath(), imageType, imageName);

        try {
            File destFile = new File(abstactPath);
            file.transferTo(destFile);
            ImageType type = ImageType.getImageTypeByName(imageType) == null ?
                    ImageType.PROFILE_BIG : ImageType.getImageTypeByName(imageType);
            FileUtil.changeImageSize(abstactPath, abstactPath, type.width, type.height);
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.debug(e.getMessage());
            return new ResultEntity<>(
                    ResultEntity.ResultStatus.FAILED.code, "Upload Image failed.");
        }

        return new ResultEntity<>(
                ResultEntity.ResultStatus.SUCCESS.code, "Upload Image success.", relativePath);
    }
}
